<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="archsw0904.controller.shopping.cart.*"%>
<%@ page import="archsw0904.controller.authentication.*"%>
<jsp:include page="/partial/process_cache.jsp" />
<jsp:useBean id="usercache" scope="session"
	class="session.cache.UserCache" />
<%
	request.setCharacterEncoding(application
			.getInitParameter("PARAMETER_ENCODING"));

	if (!usercache.isClient()) {
		response
				.sendError(401,
						"You have to be log in as a client to use this seervice");
		return;
	}

	String referer = request.getParameter("refererOverride");
	CartBeanServiceLocator cartBeanServiceLocator = new CartBeanServiceLocator();
	cartBeanServiceLocator.setCartBeanPortEndpointAddress(application
			.getInitParameter("CART_WEB_SERVICE_URI"));
	CartBean cartBeanService = cartBeanServiceLocator.getCartBeanPort();

	String addBook = request.getParameter("addBook"); //Se settato ad un ID di libro, quel libro viene aggiuto al carrello
	String removeBook = request.getParameter("removeBook"); //Se settato ad un ID di libro, quel libro viene rimosso dal carrello con tutte le copie
	String addCopy = request.getParameter("addCopy"); //Se settato ad un ID di libro, viene aggiunta una copia di quel libro dal carrello
	String removeCopy = request.getParameter("removeCopy"); //Se settato ad un ID di libro, viene rimossa una copia di quel libro dal carrello

	String checkout = request.getParameter("checkout"); /* Può avere due valori, "request" o "commit". Nel caso di request si visualizza il form
	con ida ti a cui spedire i libri (per poterli spedire), in comit vengono presi i dati a cui spedire il tutto e si crea l''ordine */
	Boolean isRequest = false, isCommit = false;

	StringBuffer errorMesssage = new StringBuffer(""); //Si appendonoa a questo buffer tutti i messagi di errore da riportare all'utente

	if (referer == null) {
		referer = request.getHeader("referer");
	}

	if (addBook != null) {
		//Devo aggiungere un libro
		try {
			cartBeanService.addBook(usercache.getUserId(), Integer
					.parseInt(addBook));
			//Redirigo alla pagina da cui mi è stato riciesto di aggiungere un libbro
			response.sendRedirect(response.encodeRedirectURL(referer));
		} catch (CartException e) {
			if (e.getEType() == ExceptionType.BookPresent) {
				errorMesssage
						.append("Please use the + and - button to change number of copies");
			} else {
				errorMesssage.append("Error: " + e.getEType());
			}
		} catch (NumberFormatException e) {
			errorMesssage.append("Error: " + addBook
					+ " non è un libro valido");
		} catch (java.lang.Exception e) {
			errorMesssage.append("Error, service not avalable " + e);
		}
	} else if (removeBook != null) {
		//Rimuovo un libro dal carrello
		try {
			cartBeanService.removeBook(usercache.getUserId(), Integer
					.parseInt(removeBook));
		} catch (CartException e) {
			errorMesssage.append("Error: " + e.getEType());
		} catch (NumberFormatException e) {
			errorMesssage.append("Error: " + removeBook
					+ " non è un libro valido");
		} catch (java.lang.Exception e) {
			errorMesssage.append("Error, service not avalable " + e);
		}
	} else if (removeCopy != null) {
		//rimouvo la copia di un libro
		try {
			cartBeanService.removeCopies(usercache.getUserId(), Integer
					.parseInt(removeCopy), 1);
		} catch (CartException e) {
			errorMesssage.append("Error: " + e.getEType());
		} catch (NumberFormatException e) {
			errorMesssage.append("Error: " + removeCopy
					+ " non è un libro valido");
		} catch (java.lang.Exception e) {
			errorMesssage.append("Error, service not avalable " + e);
		}

	} else if (addCopy != null) {
		//Rimuovo un libro dal carrello
		try {
			if (cartBeanService.addCopies(usercache.getUserId(),
					Integer.parseInt(addCopy), 1) == 0) {
				errorMesssage
						.append("There aren't any other available copies of this book");
			}
			;
		} catch (CartException e) {
			errorMesssage.append("Error: " + e.getEType());
		} catch (NumberFormatException e) {
			errorMesssage.append("Error: " + addCopy
					+ " non è un libro valido");
		} catch (java.lang.Exception e) {
			errorMesssage.append("Error, service not avalable " + e);
		}
	} else if (checkout != null) {
		if (isRequest = (checkout.compareToIgnoreCase("request") == 0)) {
			//Ricciesta di checkout, si prepare i  form per riciedere i dati a cui inviare
		} else if (isCommit = (checkout.compareToIgnoreCase("commit") == 0)) {
			//Ricciesta di effettuare il checkout con i dati conferfmati dall'utente

			//Dati a cui inviare l'ordine
			String name = request.getParameter("name");
			String surname = request.getParameter("surname");
			String state = request.getParameter("state");
			String city = request.getParameter("city");
			String cap = request.getParameter("cap");
			String address = request.getParameter("address");

			if (name != null && surname != null && state != null
					&& city != null && cap != null && address != null
					&& name.compareToIgnoreCase("") != 0
					&& surname.compareToIgnoreCase("") != 0
					&& state.compareToIgnoreCase("") != 0
					&& city.compareToIgnoreCase("") != 0
					&& cap.compareToIgnoreCase("") != 0
					&& address.compareToIgnoreCase("") != 0) {
				//Creo l'odine
				archsw0904.controller.shopping.order.OrderBeanServiceLocator orderBeanServiceLocator = null;
				archsw0904.controller.shopping.order.OrderBean orderBeanservice = null;
				archsw0904.controller.shopping.order.Orders ord = null;

				try {
					orderBeanServiceLocator = new archsw0904.controller.shopping.order.OrderBeanServiceLocator();
					orderBeanServiceLocator
							.setOrderBeanPortEndpointAddress(application
									.getInitParameter("ORDER_WEB_SERVICE_URI"));
					orderBeanservice = orderBeanServiceLocator
							.getOrderBeanPort();

					ord = orderBeanservice.createOrder(usercache
							.getUserId(), name, surname, address, cap,
							city, state);

					response.sendRedirect(application
							.getInitParameter("PAYMENT_SYSTEM_URI")
							+ "?orderId=" + ord.getId());
				} catch (archsw0904.controller.shopping.order.InvalidCartException e) {
					errorMesssage.append("Cart is not valid");
				} catch (RemoteException e) {
					errorMesssage.append("Order service says " + e);
				} catch (Exception e) {
					errorMesssage
							.append("Order service gave some problem");
					System.err.println(e);
					e.printStackTrace();
				} finally {
					//Qui ci deve arrivare solo in caso di errore, a fine try si redirige a un'altra pagina
					isRequest = true;
					isCommit = false;
				}

			} else {
				//Mancano dei dati, gli faccio reinserire i dati
				errorMesssage
						.append("Insert alla the purcase data in the form!");
				isRequest = true;
				isCommit = false;

			}
		} else {
			response.sendError(400, "checkout=" + checkout
					+ " invalid value for the confirm sequence");
			return;
		}
	}

	BookListVisualizationInfo infoCarrelo = cartBeanService
			.getBookList(usercache.getUserId());
	archsw0904.controller.shopping.cart.BookInfo infoLibri[] = infoCarrelo
			.getArrayBookInfo();
	if (infoLibri == null)
		infoLibri = new BookInfo[0];
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.rmi.RemoteException"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>View Cart @ <%=usercache.getHostingNode()%></title>
</head>
<body>
<jsp:include page="/partial/head_menu.jsp" />
<%
	if (errorMesssage.toString().compareTo("") != 0) {
%>
<p><font color="red"> <strong><%=errorMesssage%></strong> </font></p>
<%
	if (!isCommit && !isRequest) {
%>
<p><strong><a href="<%=referer%>">&lt; Back to Shopping</a></strong></p>
<br />
<%
	}
%>
<%
	}
%>

<table border="1" style="border-style: solid" cellspacing="0"
	cellpadding="3">
	<tr>
		<th>ISBN</th>
		<th>Title</th>
		<th>Author</th>
		<th>Year</th>
		<th>Price</th>
		<th>Copies</th>
		<%
			if (!isRequest) {
		%>
		<th>Remove</th>
		<%
			}
		%>
	</tr>
	<%
		for (BookInfo bi : infoLibri) {
	%>
	<tr>
		<td><%=bi.getIsbn()%></td>
		<td><%=bi.getTitle()%></td>
		<td><%=bi.getAuthor()%></td>
		<td><%=bi.getYear()%></td>
		<td><%=bi.getPrice()%> &euro;</td>
		<td>
		<table border="0">
			<tbody>
				<tr>
					<td><%=bi.getCopies()%></td>
					<%
						if (!isRequest) {
					%>
					<td>
					<form action="/BookShopWeb/page/cart.jsp" method="post"
						style="margin: 0px; padding: 0px;"><input type="hidden"
						value="<%=bi.getId()%>" name="addCopy" /> <input type="submit"
						value="+" /></form>
					</td>
					<td>
					<form action="/BookShopWeb/page/cart.jsp" method="get"
						style="margin: 0px; padding: 0px;"><input type="hidden"
						value="<%=bi.getId()%>" name="removeCopy" /> <input type="submit"
						value="-" /></form>
					</td>
					<%
						}
					%>
				</tr>
			</tbody>
		</table>
		</td>
		<%
			if (!isRequest) {
		%>
		<td>
		<form action="/BookShopWeb/page/cart.jsp" method="get"
			style="margin: 0px; padding: 0px;"><input type="hidden"
			value="<%=bi.getId()%>" name="removeBook" /> <input type="submit"
			value="Remove" /></form>
		</td>
		<%
			}
		%>
	</tr>
	<%
		}
	%>
</table>
<p><strong>Total: </strong><%=infoCarrelo.getTotalPrice()%> &euro;</p>
<%
	if (!isRequest) {
%>
<div>
<form method="post" action="/BookShopWeb/page/cart.jsp"
	style="margin: 0px; padding: 0px;"><input type="hidden"
	name="checkout" value="request" /> <input type="submit"
	value="Checkout &gt;" /></form>
</div>
<%
	} else {
		//Preparo il form con i dati della spedizione
		ProfileClient profileClient = usercache.getAuthServiceport()
				.getClientProfile(usercache.getToken());
%>
<div>
<form action="/BookShopWeb/page/cart.jsp" method="post">
<table>
	<caption><strong>Insert the purcase data</strong></caption>
	<tbody>
		<tr>
			<td><strong>Name</strong></td>
			<td><input type="text" name="name"
				value="<%=(request.getParameter("name") != null) ? request
						.getParameter("name") : profileClient.getName()%>" /></td>
		</tr>
		<tr>
			<td><strong>Surname</strong></td>
			<td><input type="text" name="surname"
				value="<%=(request.getParameter("surname") != null) ? request
								.getParameter("surname")
								: profileClient.getSurname()%>" /></td>
		</tr>
		<tr>
			<td><strong>State</strong></td>
			<td><input type="text" name="state"
				value="<%=(request.getParameter("state") != null) ? request
								.getParameter("state")
								: profileClient.getState()%>" /></td>
		</tr>
		<tr>
			<td><strong>City</strong></td>
			<td><input type="text" name="city"
				value="<%=(request.getParameter("city") != null) ? request
						.getParameter("city") : profileClient.getCity()%>" /></td>
		</tr>
		<tr>
			<td><strong>CAP</strong></td>
			<td><input type="text" name="cap"
				value="<%=(request.getParameter("cap") != null) ? request
						.getParameter("cap") : profileClient.getCap()%>" /></td>
		</tr>
		<tr>
			<td><strong>Address</strong></td>
			<td><input type="text" name="address"
				value="<%=(request.getParameter("address") != null) ? request
								.getParameter("address")
								: profileClient.getAddress()%>" /></td>
		</tr>
	</tbody>
</table>
<input type="hidden" name="checkout" value="commit" /> <input
	type="submit" value="Commit &gt;" /></form>
<h3><span
	style="border-style: dotted double; border-color: orange;">Read
Carefully befor commit!!</span></h3>
</div>
<%
	}
%>
</body>
</html>